package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api("菜品接口")
public class DishController {
    @Resource
    DishService dishService;
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @ApiOperation("新增菜品")
    @PostMapping
    public Result save(@RequestBody  DishDTO dto){
        log.info("{}",dto);
        dishService.saveWithFlavor(dto);
        Long categoryId = dto.getCategoryId();
        String key = "dish_"+categoryId;
        redisTemplate.delete(key);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO page){
        log.info("{}",page);
        PageResult pageResult = dishService.page(page);
        return Result.success(pageResult);
    }

    @DeleteMapping
    @ApiOperation("删除")
    public Result delete(@RequestParam  List<Long> ids){
        dishService.delete(ids);
        cleanCache("dish_*");
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<DishVO>  getByid(@PathVariable Long id){
        DishVO dishVO = dishService.getDishWithFlavor(id);
        return Result.success(dishVO);
    }

    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO){
        dishService.updateDishWithFlavor(dishDTO);
        cleanCache("dish_*");
        return Result.success();
    }
    @PostMapping("/status/{status}")
    public Result updateShop(@PathVariable Integer status,Long id){
        DishDTO dto = new DishDTO();
        dto.setStatus(status);
        dto.setId(id);
        dishService.updateDishWithFlavor(dto);
        cleanCache("dish_*");
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("通过分类id查询菜品")
    public Result<List<Dish>> getDishByCategoryId(Long categoryId){
        log.info("分类id {}",categoryId);
      List<Dish> list =  dishService.getDishByCategoryId(categoryId);
      return Result.success(list);
    }

    private void cleanCache(String key){
        Set<String> keys = redisTemplate.keys(key);
        if (keys != null) {
            redisTemplate.delete(keys);
        }
    }
}
